import 'dart:async';

import 'package:built_collection/built_collection.dart';
import 'package:equatable/equatable.dart';
import 'package:mobile_app.core/core/domain/entities/learning_content/collection_list_item/collection_list_item.dart';
import 'package:mobile_app.core/core/domain/repositories/learning_content_repository/repository.dart';
import 'package:mobile_app.home.core/core/domain/helpers/apply_collection_list_item_update/helper.dart';

part 'result.dart';

abstract class ChangeCollectionSorting {
  CollectionSortingChangeResult call({
    required CollectionSorting sorting,
    required Collection collection,
    required BuiltList<CollectionListItem> collectionListItems,
  });
}

class ChangeCollectionSortingImpl implements ChangeCollectionSorting {
  const ChangeCollectionSortingImpl({
    required ApplyCollectionListItemUpdate applyCollectionListItemUpdate,
    required LearningContentRepository learningContentRepository,
  })  : _applyCollectionListItemUpdate = applyCollectionListItemUpdate,
        _learningContentRepository = learningContentRepository;

  final ApplyCollectionListItemUpdate _applyCollectionListItemUpdate;
  final LearningContentRepository _learningContentRepository;

  @override
  CollectionSortingChangeResult call({
    required CollectionSorting sorting,
    required Collection collection,
    required BuiltList<CollectionListItem> collectionListItems,
  }) {
    final updatedCollection = collection.copyWith(
      sorting: () => sorting,
    );

    final updatedCollectionListItems = _applyCollectionListItemUpdate(
      updatedCollectionListItem: updatedCollection,
      collectionListItems: collectionListItems,
    );

    final result = CollectionSortingChangeResult(
      collection: updatedCollection,
      collectionListItems: updatedCollectionListItems,
    );

    unawaited(_learningContentRepository.saveCollectionListItems(
      collectionListItems: updatedCollectionListItems,
    ));

    return result;
  }
}
